package cmd

import (
	"errors"
	l4g "github.com/alecthomas/log4go"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"mysqlbackup/cron"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
)

type Config struct {
	Work string
	Crons []cron.CronConfig
	FullConfig FullConfig
	DBconfig DBconfig
	IncrementalConfig IncrementalConfig
}


func GetCurrentPath() (string, error) {
	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		return "", err
	}
	path, err := filepath.Abs(file)
	if err != nil {
		return "", err
	}
	//fmt.Println("path111:", path)
	if runtime.GOOS == "windows" {
		path = strings.Replace(path, "\\", "/", -1)
	}
	//fmt.Println("path222:", path)
	i := strings.LastIndex(path, "/")
	if i < 0 {
		return "", errors.New(`Can't find "/" or "\".`)
	}
	//fmt.Println("path333:", path)
	return string(path[0 : i+1]), nil
}
func  getConfig(path string) (Config,error){
	var configF Config
	config := viper.New()
	config.AddConfigPath(path)
	config.SetConfigName("config")
	config.SetConfigType("yaml")
	if err := config.ReadInConfig(); err != nil {
		return configF,err
	}
	if err :=config.Unmarshal(&configF);err !=nil{
		return configF,err
	}
	config.WatchConfig()
	config.OnConfigChange(func(e fsnotify.Event) {
		Reload(config,e)
	})
	return configF,nil
}

func Reload(vp *viper.Viper, e fsnotify.Event)  {
	err := vp.Unmarshal(&config)
	if err != nil {
		l4g.Error(err)
	}
	err =c.AddAll(config.Crons)
	if err != nil {
		l4g.Error(err)
	}
}